<?php

namespace app\admin\controller;

use app\admin\controller\AdminBase;
use app\admin\model\Page;
use app\common\model\ExcelModel;
use app\common\model\RoleModel;
use app\common\model\UserAndRoleModel;
use app\common\model\UserModel;

/**
 * 用户管理
 *     针对前端 用户 的所有操作
 * 
 * 时间 ： 2020年4月4日23:07:51
 * 作者 ： 夏立军
 */
class User extends AdminBase
{
    // 首页
    public function index()
    {
        $user = new UserModel();
        $user_count = $user->get_user_count();
        $size = config('ams_config.user_page_size');

        $page = new Page();
        $page_res = $page->getPageRes($user_count, $size, url('index'));

        $user_list = $user->user_list_page($page_res['offset'], $page_res['size']);

        return view('index', [
            // 分类列表
            'user_list' => $user_list,
            // 若分类无数据，则输出设置的样式
            'empty' => '<tr><td colspan="7" style="text-align: center;">没有数据</td></tr>',
            // 分页的处理结果
            'page_res' => $page_res,
        ]);
    }

    // 添加用户
    public function user_add()
    {

        if (Request()->post()) {

            $account = input('post.account/s', null);
            $name = input('post.name/s', null);

            if (is_null($account) || is_null($name)) {
                return json(['code' => 1, 'msg' => '数据不能为空']);
            }

            if (mb_strlen($account) < 4) {
                return json(['code' => 2, 'msg' => '账号不能小于4位']);
            }

            if (mb_strlen($name) < 2) {
                return json(['code' => 3, 'msg' => '姓名不能小于2位']);
            }

            $user = new UserModel();
            $user_info = $user->get_user_info_by_account($account);
            if ($user_info) {
                return json(['code' => 4, 'msg' => '用户名已存在']);
            }

            $password = md5('123456' . config('ams_config.user_password_suffix'));
            $user_res = $user->register_user($account, $password, $name);
            if (!$user_res) {
                return json(['code' => 5, 'msg' => '注册失败，联系管理员']);
            }

            return json(['code' => 0, 'msg' => '添加完成']);
        }

        return view('user_add', []);
    }

    // 编辑用户
    public function user_edit()
    {
        if (request()->post()) {

            $id = input('post.id/d', null);
            $name = input('post.name/s', null);
            $age = input('post.age/d', null);
            $position = input('post.position/s', null);
            $tel = input('post.tel/s', null);
            $phone = input('post.phone/s', null);
            $email = input('post.email/s', null);
            $qq = input('post.qq/s', null);
            $wx = input('post.wx/s', null);
            $address = input('post.address/s', null);

            $data['name'] = $name;
            $data['age'] = $age;
            $data['position'] = $position;
            $data['tel'] = $tel;
            $data['phone'] = $phone;
            $data['email'] = $email;
            $data['qq'] = $qq;
            $data['wx'] = $wx;
            $data['address'] = $address;
            $data['update_time'] = time();

            $user = new UserModel();
            $user_res = $user->set_user_info($id, $data);
            if (!$user_res) {
                return json(['code' => 1, 'msg' => '修改失败，【手机/邮箱/QQ/微信】可能与其他人重复']);
            }

            return json(['code' => 0, 'msg' => '修改成功']);
        }

        $uid = input('get.uid/d', null);
        if (is_null($uid)) {
            return redirect_index('未传入用户ID', url('User/index'));
        }
        $user = new UserModel();
        $user_res = $user->get_user_info_by_id($uid);

        if (is_null($user_res)) {
            return redirect_index('未传入用户ID', url('User/index'));
        }

        return view('user_edit', [
            'user_info' => $user_res,
        ]);
    }

    // 删除一个用户
    public function user_del()
    {
        if (request()->post()) {
            $uid = input('post.uid/d', null);
            if (is_null($uid)) {
                return json(['code' => 1, 'msg' => 'ID丢失，请刷新重新点击']);
            }

            $user = new UserModel();
            $user_res = $user->del_user_info_by_id($uid);
            if (!$user_res) {
                return json(['code' => 2, 'msg' => '该用户下有数据无法直接删除【有成果，或者有权限】']);
            }
            return json(['code' => 0, 'msg' => '删除成功']);
        }
        return json(['code' => 99, 'msg' => '请求模式错误']);
    }

    // 角色用户关联页面
    public function user_role()
    {
        $uid = input('get.uid/d', null);
        if (is_null($uid)) {
            return redirect_index('未传入用户ID', url('User/index'));
        }

        $user = new UserModel();
        $user_info = $user->get_user_info_by_id($uid);
        if (!$user_info) {
            return redirect_index('该用户不存在', url('User/index'));
        }

        $role = new RoleModel();
        $role_info = $role->get_all_role();

        $user_role = new UserAndRoleModel();
        $user_role_info = $user_role->get_user_role_info($uid);

        return view('user_role', [
            // 用户信息
            'user_info' => $user_info,
            // 角色信息
            'role_info' => $role_info,
            // 已有权限信息
            'user_role_info' => $user_role_info,
        ]);
    }

    // 授权
    public function add_user_role()
    {
        if (request()->post()) {
            $uid = input('post.uid/d', null);
            $rid = input('post.rid/d', null);

            if (is_null($uid) || is_null($rid)) {
                return json(['code' => 1, 'msg' => '授权失败，请刷新重试']);
            }

            $aid = session('admin_login')->id;
            $user_role = new UserAndRoleModel();
            $res = $user_role->add_user_role($aid, $uid, $rid);
            if (!$res) {
                return json(['code' => 2, 'msg' => '该角色已存在']);
            }

            return json(['code' => 0, 'msg' => '授权成功']);
        }
        return json(['code' => 99, 'msg' => '请求模式错误']);
    }

    // 取消授权
    public function del_user_role()
    {
        if (request()->post()) {
            $user_role_id = input('post.id/d', null);
            if (is_null($user_role_id)) {
                return json(['code' => 1, 'msg' => '取消失败，请刷新重试']);
            }

            $user_role = new UserAndRoleModel();
            $res = $user_role->del_user_role($user_role_id);
            if (!$res) {
                return json(['code' => 2, 'msg' => '取消失败，请刷新重试']);
            }

            return json(['code' => 0, 'msg' => '取消授权成功']);
        }
        return json(['code' => 99, 'msg' => '请求模式错误']);
    }

    // 重置密码
    public function re_password()
    {
        if (request()->post()) {
            $uid = input('post.uid/d', null);
            if (is_null($uid)) {
                return json(['code' => 1, 'msg' => 'ID丢失，请刷新重新点击']);
            }
            $user = new UserModel();
            $re_pwd = config('ams_config.re_password')??'123456';
            $password = md5($re_pwd . config('ams_config.user_password_suffix'));
            $user_res = $user->re_password($uid, $password);
            if (!$user_res) {
                return json(['code' => 2, 'msg' => '重置失败']);
            }

            return json(['code' => 0, 'msg' => '重置完成 密码为：' . $re_pwd]);
        }
        return json(['code' => 99, 'msg' => '请求模式错误']);
    }

    // 模板下载
    public function user_import_tmp_download()
    {
        return json(['status' => true, 'url' => "/static/excel/用户导入模板.xlsx"]);
    }

    // 用户批量导入
    public function user_import()
    {
        $file = request()->file('user_data');
        $file = iconv("utf-8", "gb2312", $file);

        if (empty($file) or !file_exists($file)) {
            return ['code' => 1, 'msg' => '文件不存在!'];
        }

        $excel_model = new ExcelModel();
        $excel = $excel_model->validationExcel($file);
        if (is_null($excel)) {
            return json(['code' => 2, 'msg' => '只能上传excel的文件!']);
        }

        $spreadsheet = $excel->load($file);
        $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // 总行数
        $highestColumn = $worksheet->getHighestColumn(); // 总列数

        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return json(['code' => 3, 'msg' => 'Excel表格中没有数据!']);
        }

        $user = new UserModel();
        $time = time();
        $data = array();
        for ($row = 2; $row <= $highestRow; ++$row) {
            $account = $worksheet->getCellByColumnAndRow(1, $row)->getValue(); //用户账号
            $account = empty($account) ? '' : strval($account);

            $name = $worksheet->getCellByColumnAndRow(2, $row)->getValue(); //用户名称
            $name = empty($name) ? '' : strval($name);

            $tel = $worksheet->getCellByColumnAndRow(3, $row)->getValue(); //办公室电话
            $tel = empty($tel) ? '' : strval($tel);

            $phone = $worksheet->getCellByColumnAndRow(4, $row)->getValue(); //手机
            $phone = empty($phone) ? '' : strval($phone);

            $address = $worksheet->getCellByColumnAndRow(5, $row)->getValue(); //办公室地址
            $address = empty($address) ? '' : strval($address);

            if ($account == '' || $name == '') {
                return json(['code' => 4, 'msg' => '账号或昵称不能为空']);
            }

            $user_info = $user->user_data_import_by_excel($account, $name, $tel, $phone, $address, $time);
            if (!$user_info) {
                $data[] = $account;
            }
        }
        if ($data) {
            return json(['code' => 5, 'msg' => '某些账号注册失败', 'data' => $data]);
        }
        return json(['code' => 0, 'msg' => '导入数据完成，并注册完成']);
    }
}
